/**
 * 组顶部选项卡
 */

import React from 'react';
import { Button, Badge } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import Nav from '@alife/yunxiao-uiless-extendable-nav';
import { navigate } from 'utils/router';
import MemberList from 'components/memberList';
import { GROUP_ADMIN_ROLES, ENUM } from 'utils/constants.js';
import AccessContainer from 'components/accessContainer';

import './index.scss';
import intl from '../../../../../../locale';

export default class GroupTab extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hiddenKeys: [],
      hideSetting: false,
      hideMember: false,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    const { projectInfo, isProjectInfoFetched } = (nextProps.group && nextProps.group.root) || {};
    if (!isProjectInfoFetched) {
      return {};
    }
    const pageInfo = (nextProps.root && nextProps.root.pageInfo) || {};
    if (!pageInfo.pathResource) {
      return;
    }
    // 若库为空，则隐藏以下tab 或者导入状态为failed(初始化空库状态failed不变，结合isExist进行判断)/started
    const isImportUnfinished =
      projectInfo.import_status === 'started' ||
      projectInfo.import_status === 'stopping' ||
      (projectInfo.import_status === 'failed' && pageInfo.pathResource.isExist === 'false');
    const hiddenKeys =
      isImportUnfinished || pageInfo.pathResource.isEmpty === 'true'
        ? ['merge', 'commits', 'mergerequest', 'branches', 'tags', 'security']
        : [];
    let hideMember = false;
    const extendable = !isImportUnfinished;
    if (projectInfo.import_status === 'started' || projectInfo.import_status === 'stopping') {
      hideMember = true;
    }
    // 在库内，状态是none、finished、failed，并且isExist==true时，并且有权限时，展示设置入口
    const hideSetting = !(
      ['none', 'finished', 'failed'].includes(projectInfo.import_status) &&
      pageInfo.pathResource.isExist === 'true'
    );
    return {
      hiddenKeys,
      hideMember,
      hideSetting,
      extendable,
    };
  }

  onClick = (key) => {
    // TODO 此处有硬编码，待应用中心解决
    const { pathResource } = window.FORCE;
    const APP_URL_ENUM = {
      wiki: `/${pathResource.fullPath}/wiki`,
      ForceWiki: `/${pathResource.fullPath}/wiki`,
      文档: `/${pathResource.fullPath}/wiki`,
    };

    const dataSource = this.getDataSource();

    let jumpUrl;
    if (APP_URL_ENUM[key]) {
      jumpUrl = APP_URL_ENUM[key];
    } else {
      const data = dataSource.find((item) => item.key === key);
      jumpUrl = data.href;
    }
    navigate(jumpUrl);
  };

  // 由资源名判断高亮哪个tab
  getActiveKeyFromAssetsName = () => {
    const { assetsName } = window.FORCE;
    const dataSource = this.getDataSource();
    const key = assetsName.replace('group', '').toLocaleLowerCase();
    let result;
    if (dataSource.some((item) => item.key === key)) {
      result = key;
    } else {
      switch (key) {
        case 'settings':
          result = 'settings';
          break;
        default:
          break;
      }
    }

    return result;
  };

  getDataSource = () => {
    const { hiddenKeys } = this.state;
    const { pathResource } = window.FORCE;
    const { groupCount, mergeRequestCount } = pathResource;

    const dataSource = [
      {
        key: 'home',
        title: intl.get({
          id: 'code-assets.containers.tab.SubgroupsAndDatabases',
          defaultMessage: '子组与库',
        }),
        badge: groupCount ? <Badge count={groupCount} /> : null,
        href: `/${pathResource.fullPath}`,
      },

      {
        key: 'mergerequest',
        title: intl.get({
          id: 'code-assets.containers.tab.MergeRequest',
          defaultMessage: '合并请求',
        }),
        badge: mergeRequestCount ? <Badge count={mergeRequestCount} /> : null,
        href: `/${pathResource.fullPath}/merge_requests`,
      },

      {
        key: 'activity',
        title: intl.get({
          id: 'code-assets.containers.tab.SummaryInvestingComZa',
          defaultMessage: '概览',
        }),
        href: `/${pathResource.fullPath}/activity`,
      },
    ];

    const shownDataSource = dataSource.filter((item) => {
      return !hiddenKeys.includes(item.key);
    });
    return shownDataSource;
  };

  renderExtra = (activeKey) => {
    const { pathResource } = window.FORCE;
    const { role, type } = pathResource;
    const { hideMember, hideSetting } = this.state;
    return (
      <div>
        {!hideMember && type !== ENUM.path_resource_type.PERSONAL_NAMESPACE ? (
          <MemberList
            trigger={
              <Button text>
                <YunxiaoIcon type="member-line" />
                {intl.get({ id: 'code-assets.containers.tab.Members', defaultMessage: '成员' })}
              </Button>
            }
            pathResourceId={pathResource.id}
            pathResourceType="group"
            align="tr br"
            role={pathResource.role}
          />
        ) : null}
        {!hideSetting && (
          <AccessContainer neededRole={GROUP_ADMIN_ROLES} role={role}>
            <Button
              text
              component="a"
              onClick={() => {
                navigate(`/${pathResource.fullPath}/settings`);
              }}
              className={`project-tab-settings ${activeKey === 'settings' ? 'active' : ''}`}
              style={{ marginLeft: 16 }}
            >
              <YunxiaoIcon type="setting-line" />
              {intl.get({ id: 'code-assets.containers.tab.Set', defaultMessage: '设置' })}
            </Button>
          </AccessContainer>
        )}
      </div>
    );
  };

  render() {
    const { activeKey } = this.props;
    const { pathResource } = window.FORCE;
    const { role } = pathResource;
    const dataSource = this.getDataSource();

    const pageInfo = (this.props.root && this.props.root.pageInfo) || {};

    if (!pageInfo.pathResource) {
      return null;
    }

    const curActiveKey = activeKey || this.getActiveKeyFromAssetsName();

    return (
      <Nav
        triggerType="click"
        {...this.props}
        onClick={this.onClick}
        extendable={false}
        extra={this.renderExtra(curActiveKey)}
        className="project-tab"
        activeKey={curActiveKey}
        dataSource={dataSource}
        objectId={pathResource.id}
        objectType="Repository"
        identifier="app_for_code"
        isAdmin={GROUP_ADMIN_ROLES.includes(role)}
      />
    );
  }
}
